/**
 * 
 */
package org.dg.iag.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.dg.iag.dao.GenericDAO;
import org.dg.iag.entity.ImportLogStatus;
import org.dg.iag.entity.Log;
import org.dg.iag.entity.Logs;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.server.LogsServerResource.LogsResource;
import org.dg.iag.util.ApplicationConstants;
import org.dg.iag.util.ImportManager;
import org.dg.iag.util.ImportThread;
import org.dg.iag.util.LoginUtil;
import org.dg.iag.util.RestletUtil;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

/**
 * @author Alex Gartner
 * 
 *
 */
public class ImportFeedsServerResource extends ServerResource {
	
	public static Logger logger	= Logger.getLogger(ImportFeedsServerResource.class.getName() );
	
	@Get
	public Object action() {
		if ( ! LoginUtil.checkLogin(getRequest()) ) 
			return null;
		String action			= (String)this.getRequest().getAttributes().get("actionName");
		
		if ( "reloadAll".equals(action) ) {
			return new ImportManager().reloadAll();
		}
		
		if ( "checkStatus".equals(action) ) {
			ImportLogStatus ils		= ImportLogStatus.getInstance();
			if ( ils.getFinished() == null || ils.getFinished() ) 
				return ils;
			
			String checkedFeedNoStr	= (String)this.getRequest().getAttributes().get("param1");
			int checkedFeedNo		= 0; 
			try {
				checkedFeedNo 	= Integer.parseInt(checkedFeedNoStr);
			} catch (Exception e) {
				logger.warning(e.getMessage());
			}
			int newFeedNo			= ils.getCurrentTagNo()!=null ? ils.getCurrentTagNo():0;
			long currentTime		= System.currentTimeMillis();
			long newTime			= currentTime;
			while (checkedFeedNo == newFeedNo && newTime-currentTime < ApplicationConstants.AJAX_MAX_CONNECTION_TIME){
				newFeedNo				= ils.getCurrentTagNo()!=null ? ils.getCurrentTagNo():0;
				newTime					= System.currentTimeMillis();
				try {
					Thread.sleep(ApplicationConstants.AJAX_CHECK_WAIT_TIME);
				} catch (InterruptedException e) {
					logger.severe(e.getMessage());
					e.printStackTrace();
				}
			}
			
			return ils;
		} 
		if ( "stopImport".equals(action) ) {
			if ( ImportThread.importThread != null && ImportThread.importThread.isAlive() )
				ImportThread.importThread.stop.set(true);
		}
		
		if ( "loadFailed".equals(action) ) {
			ImportLogStatus ils		= ImportLogStatus.getInstance();
			if ( ils.getFinished() != null && !ils.getFinished() )  {//Something is still running 
				logger.warning("There is already an import running. If you are creating scheduled jobs please make sure they don't overlap.");
				return ils;
			}
			ils.setFinished(false);
			String logId	= (String) this.getRequest().getAttributes().get("param1");
			
			return new ImportManager().reloadFailed(logId);
		}
		
		return "Working";
	}
	
	
}
